<?php
/**
 * https://gitee.com/Mao02
 * http://blog.dazhetu.cn/
 * jay_fun 410136330@qq.com
 * Date: 2018/6/7
 * Time: 16:10
 */
namespace app\admin\controller;

use app\common\controller\BasicAdmin;
use think\Db;
use think\facade\Request;

/**
 * @title 广告内容管理
 * Class Adscont
 * @package app\admin\controller
 */
class Ads extends BasicAdmin
{
    protected $table = "ContentAds";

    /**
     * @title 列表页
     * @return array|mixed|\PDOStatement|string|\think\Collection
     */
    public function index()
    {
        $db = Db::name($this->table)
            ->alias('a')
            ->join('__CONTENT_ADSCATE__ c','c.id = a.cid','LEFT')
            ->field('a.*,c.title as ctitle')
            ->where('a.is_deleted','=',0);

        $search = Request::get();
        // 精准查询
        foreach (['state','cid'] as $field){
            if (isset($search[$field]) && $search[$field] !== ''){
                $db->where("a.{$field}",'=', $search[$field]);
            }
        }
        // 模糊查询
        foreach (['title'] as $field){
            if (isset($search[$field]) && $search[$field] !== ''){
                $db->whereLike("a.{$field}", "%{$search[$field]}%");
            }
        }

        return $this->_list($db, true, $search);
    }

    public function _index_list_before()
    {
        $cates=Db::name('ContentAdscate')
            ->field('id,title')
            ->where('is_deleted',0)
            ->select();
        $this->assign('cates', $cates);
    }

    /**
     * @title 添加
     * @return mixed
     */
    public function add()
    {
        return $this->_form('', 'form');
    }

    /**
     * @title 编辑
     * @return mixed
     */
    public function edit()
    {
        return $this->_form('', 'form');
    }

    /**
     * @title 删除
     * @throws PDOException
     * @throws \think\Exception
     */
    public function del()
    {
        $ids = Request::get('ids');
        $this->_del($ids);
    }

    /**
     * @title 禁用/启用操作
     * @throws \think\Exception
     */
    public function change()
    {
        $id = Request::get('id');
        $state = Request::get('state');
        $this->_change($id, ['state' => $state]);
    }

    public function _form_before(&$data)
    {
        if (Request::isGet()){
            $cates=Db::name('ContentAdscate')
                ->field('id,title')
                ->where('is_deleted',0)
                ->where('state',1)
                ->select();
            $this->assign('cates', $cates);
        }else{
            if (!isset($data['id'])){
                $data['create_time'] = Request::time();
            }
        }
    }
}